package com.saibo.spider.commons;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class ConnectServer {
	
	/**
	 * 用于提交数据与请求数据使用
	 * @param url
	 * @param value
	 * @return
	 */
	public static String sendPostRequest(String url , String value) {
		try {
			HttpClient client = HttpClients.createDefault();
			RequestConfig requestConfig = RequestConfig.custom()
			        .setSocketTimeout(1000)
			        .setConnectTimeout(1000)
			        .build();
			HttpPost post = new HttpPost(url);
			StringEntity entity = new StringEntity(value,"UTF-8");
			entity.setContentEncoding("UTF-8");
			entity.setContentType("application/json");// 设置为 json数据
			post.setEntity(entity);
			post.setConfig(requestConfig);
			HttpResponse response = client.execute(post);
			if(null==response){
				return null;
			}
			HttpEntity resEntity = response.getEntity();
			if(null ==resEntity){
				return null;
			}
			String res = EntityUtils.toString(resEntity);
			return res;
		} catch (Exception e) {
			return null;
		}
	}
}
